﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace NTUTMessagerAPI
{
    class AES_API
    {
        static public byte[] AESEncoder(byte[] source, int key)  //AES 加密函數
        {
            

            byte[] bkey = new byte[32];
            byte[] iv = new byte[16];
            byte[] shaBuffer = new SHA384Managed().ComputeHash(BitConverter.GetBytes(key));
            RijndaelManaged aes = new RijndaelManaged();

            Array.Copy(shaBuffer, 0, bkey, 0, 32);
            Array.Copy(shaBuffer, 32, iv, 0, 16);

            ICryptoTransform ict = aes.CreateEncryptor(bkey, iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
            byte[] rawData = (byte[])source.Clone();

            cs.Write(rawData, 0, rawData.Length);
            cs.Close();

            if (source.Length > 4)
            {
                Console.WriteLine("** AES 加密　[" + RSA_API.ByteToString(source) + "] => [" + RSA_API.ByteToString(ms.ToArray()) + "]");
            }

            return ms.ToArray();
        }

        static public byte[] AESDecoder(byte[] source, int key)  //AES 解密函數
        {
            byte[] rawData = (byte[])source.Clone();
            byte[] bkey = new byte[32];
            byte[] iv = new byte[16];
            byte[] shaBuffer = new SHA384Managed().ComputeHash(BitConverter.GetBytes(key));
            //Console.WriteLine(shaBuffer.Length);
            RijndaelManaged aes = new RijndaelManaged();

            Array.Copy(shaBuffer, 0, bkey, 0, 32);
            Array.Copy(shaBuffer, 32, iv, 0, 16);

            ICryptoTransform ict = aes.CreateDecryptor(bkey, iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
          
            cs.Write(rawData, 0, rawData.Length);
            cs.Close();

            if (ms.ToArray().Length > 4)
            {
                Console.WriteLine("** AES 解密　[" + RSA_API.ByteToString(source) + "] => [" + RSA_API.ByteToString(ms.ToArray()) + "]");
            }


            return ms.ToArray();
        }
    }
}
